const modules = {};
const exports = {}; // 缓存模块
const module = this;
const seajs = {};

const getUrl = (name) => {
  // eslint-disable-next-line no-restricted-globals
  const pathname = location.pathname;
  return pathname.slice(0, pathname.lastIndexOf('/')) + '/' + name + '.js';
};
/**
 * 实现以下几个方法
 * define全局方法
 * require全局方法
 * rj全局对象
 */
const def = new Map();
const defaultOptions = {
  paths: '',
};

// 加载cdn链接
const __import = (url) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-restricted-properties
    System.import(url).then(resolve, reject);
  });
};

const __load = (url) => {
  return new Promise((r, reject) => {
    /* const head = document.getElementsByName('head');
    const srciptDom = document.createElement('script');
    srciptDom.url = url;
    srciptDom.type = 'text/javascript';
    srciptDom.async = true;
    srciptDom.onload = r;
    srciptDom.onerror = reject;
    head.appendChild(srciptDom); */
    const head = document.getElementsByTagName('head')[0];
    const node = document.createElement('script');
    node.type = 'text/javascript';
    node.src = url;
    node.async = true;
    node.onload = r;
    node.onerror = reject;
    head.appendChild(node);
  });
};

// 真正加载模块的方法
const __require = (id) => {};

seajs.use = function (mods, factory) {
  return new Promise((resolve, reject) => {
    mods = Array.isArray(mods) ? mods : [mods];
    Promise.all(
      mods.map((mod) => {
        return __load(getUrl(mod)).then({});
      })
    );
  }).then((deps) => factory(...deps));
};

const __getUrl = (name) => {
  // eslint-disable-next-line no-restricted-globals
  const pathname = location.pathname;
  return pathname.slice(0, pathname.lastIndexOf('/')) + '/' + name + '.js';
};
// 加载javascript文件

window.rj = {
  config: function (options) {
    return Object.assign(defaultOptions, options);
  },
};

// 依赖收集
window.define = function (name, deps, factory) {
  def.set(name, {
    name,
    deps,
    factory,
  });
};

window.require = () => {};
